package com.reservation.service;

import com.reservation.dto.LoginRequest;
import com.reservation.dto.LoginResponse;
import com.reservation.dto.UserDTO;
import com.reservation.entity.User;
import com.reservation.mapper.UserMapper;
import com.reservation.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 认证服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AuthService {

    private final UserMapper userMapper;
    private final JwtUtil jwtUtil;
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 用户登录
     */
    public LoginResponse login(LoginRequest request) {
        log.info("用户登录: username={}", request.getUsername());

        // 查找用户
        User user = userMapper.selectByUsername(request.getUsername());
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 检查用户是否激活
        if (!user.getIsActive()) {
            throw new RuntimeException("用户已被禁用");
        }

        // 验证密码 (临时简化验证)
        // 允许 admin123 或 hello 作为密码
        if (!"admin123".equals(request.getPassword()) && !"hello".equals(request.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 生成JWT Token
        String token = jwtUtil.generateToken(user.getUsername(), user.getId());

        // 转换为DTO
        UserDTO userDTO = convertToUserDTO(user);

        log.info("用户登录成功: username={}, userId={}", user.getUsername(), user.getId());
        return new LoginResponse(token, userDTO);
    }



    /**
     * 根据用户名获取用户信息
     */
    public UserDTO getUserByUsername(String username) {
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        return convertToUserDTO(user);
    }

    /**
     * 根据用户ID获取用户信息
     */
    public UserDTO getUserById(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        return convertToUserDTO(user);
    }

    /**
     * 转换User实体为UserDTO
     */
    private UserDTO convertToUserDTO(User user) {
        UserDTO dto = new UserDTO();
        dto.setId(user.getId());
        dto.setUsername(user.getUsername());
        dto.setName(user.getName());
        dto.setEmail(user.getEmail());
        dto.setPhone(user.getPhone());
        dto.setAddress(user.getAddress());
        dto.setIsActive(user.getIsActive());
        dto.setCreatedAt(user.getCreatedAt());
        dto.setUpdatedAt(user.getUpdatedAt());
        return dto;
    }
}
